package org.sakai.util;

import io.jsonwebtoken.*;

import java.io.*;
import java.util.Date;
import java.util.Map;

public class UserUtils {
    private static final String jwtSecretKey;
    static {
        try (InputStream is = UserUtils.class.getClassLoader().getResourceAsStream("jwtSignToken")) {
            if (is == null) {
                throw new RuntimeException("File not found in classpath: jwtSignToken");
            }

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                jwtSecretKey = reader.readLine();
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to load jwtSignToken file", e);
        }
    }

    public static String createToken(Map<String, Object> claims) {
        JwtBuilder jwtBuilder = Jwts.builder()
                // 设置有效载荷
                .setClaims(claims)
                // 设置签发时间
                .setIssuedAt(new Date())
                // 设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 7 * 1000))
                // 采用HS256方式签名，key就是用来签名的秘钥
                .signWith(SignatureAlgorithm.HS256, jwtSecretKey);
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token，如果出现签名被修改、token过时等会报错，否则正确返回数据
     * @param token
     * @return
     * @throws ExpiredJwtException
     * @throws MalformedJwtException
     * @throws SignatureException
     */
    public static Map<String, Object> checkToken(String token) throws ExpiredJwtException,MalformedJwtException, SignatureException{
            Jwt parse = Jwts.parser().setSigningKey(jwtSecretKey).parse(token);
            return (Map<String, Object>) parse.getBody();
    }
    /**
     * 检验邮箱格式是否正确
     * @param email
     * @return
     */
    public static boolean checkEmail(String email){
        if (email == null || email.isEmpty()) {
            return false;
        }
        // 邮箱正则表达式
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        return email.matches(emailRegex);
    }
    /**
     * 检验电话
     * @param phone
     * @return
     */
    public static boolean checkPhone(String phone){
        return true;
    }
    /**
     * 检验密码
     * 检查密码长度是否在 8 到 15 字符之间；
     * 遍历每个字符，判断是否包含字母和数字；
     * 若同时满足上述条件，则返回 true，否则返回 false。
     * @param password
     * @return
     */
    public static boolean checkPassword(String password){
        if (password == null || password.length() < 8 || password.length() > 15) {
            return false;
        }

        boolean hasLetter = false;
        boolean hasDigit = false;

        for (char c : password.toCharArray()) {
            if (Character.isLetter(c)) {
                hasLetter = true;
            } else if (Character.isDigit(c)) {
                hasDigit = true;
            }
        }
        return hasLetter && hasDigit;
    }
    public static String getRandomUserName(){
        String res = "";
        for(int i = 0;i < 12; i++){
            res +=  Math.round(Math.random()) == 1L?(char)('a' + 26 * Math.random()):(char)('A' + 26 * Math.random());
        }
        return res;
    }
}
